(defun primep (n)
 ; (declare (optimize (speed 3) (safety 0)))
 ; (declare (fixnum n))
  (cond ((<= n 3) t)
	((zerop (mod n 2)) nil)
	(t (loop 
	      for i = 3 then (+ i 2)
	      until (> i (isqrt n))
	      when (zerop (mod n i)) 
	      do (return nil) 
	      finally (return t)))))

(defun next-primep(p)
  (loop for i = (1+ p) then (1+ i) 
     until (primep i) 
     finally (return i)))



(defun find-sum(max-length sum-length sum-value small big)
  (let ((nextbig (next-primep big))
	(nextsmall (next-primep small)))
    (cond ((> sum-value 1000000) 
	   (print 0))
	  ((< sum-length max-length)
	   (find-sum max-length (1+ sum-length) (+ sum-value nextbig) small nextbig))
	  ((and (= sum-length max-length) (primep sum-value)) 
	   sum-value)
	  ((and (= sum-length max-length) (not (primep sum-value)))
	   (find-sum max-length sum-length (+ (- sum-value small) nextbig) nextsmall nextbig))
	  (t (print "oooops")))))

;(require 'memoize)	  
;(memoize:MEMOIZE-FUNCTION 'primep)
;(memoize:MEMOIZE-FUNCTION 'next-primep)
;(memoize:MEMOIZE-FUNCTION 'find-sum)

(defun probl50()
  (loop for i from 20 to 1000 maximize (find-sum i 0 2 2 2)))